﻿

namespace Document.Library
{
    using System;
    using System.Drawing;
    using System.IO;

    /// <summary>
    /// Base64帮助操作类
    /// </summary>
    public class Base64Helper
    {

        /// <summary>
        /// 根据Byte转为base64编码字符串
        /// </summary>
        /// <param name="arr">byte数组</param>
        /// <returns>base64编码字符串</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static string ByteToBase64String(byte[] arr)
        {
            try
            {
                return Convert.ToBase64String(arr);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 指定一个本地图片路径，
        /// 返回该图片数据的base64编码字符串，
        /// 如果路径不正确，则返回一个空字符串
        /// </summary>
        /// <param name="imagefilePath">图片的全路径</param>
        /// <returns>base64编码字符串</returns>
        /// <exception cref="Exception"></exception>
        public static string ImgToBase64String(string imagefilePath)
        {
            try
            {
                string strbaser64 = string.Empty;
                if (!File.Exists(imagefilePath)) return strbaser64;
                using (FileStream fileStream = File.OpenRead(imagefilePath))
                {
                    using (BinaryReader binReader = new BinaryReader(fileStream))
                    {
                        byte[] bytes = binReader.ReadBytes(Convert.ToInt32(fileStream.Length));
                        strbaser64 = Convert.ToBase64String(bytes);
                    }
                }
                return strbaser64;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 将base64编码字符串转换成byte数组
        /// </summary>
        /// <param name="base64StringData">使用base编码的字符串数据</param>
        /// <returns>转换的byte数组</returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="FormatException"></exception>
        public static byte[] Base64StringToByte(string base64StringData)
        {
            try
            {
                return Convert.FromBase64String(base64StringData);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// base64转位图（一定要bmp.Dispose()）
        /// </summary>
        /// <param name="base64"></param>
        /// <returns></returns>
        public static Bitmap Base64ToImage(string base64)
        {
            base64 = base64.Replace("\\n", "\n").Replace(" ", "+");
            byte[] arr = Convert.FromBase64String(base64);
            using (MemoryStream outMs = new MemoryStream(arr))
            {
                using (Bitmap bmp = new Bitmap(outMs))
                {
                    return bmp;
                }
            }
        }
    }
}
